import { defineStore } from 'pinia'

export const useTabsStore = defineStore('tabs', {
    state: () => ({
        tabs: [
            {
                title: '首页',
                path: '/setting/users'
            }
        ],
        activeTab: '/setting/users'
    }),
    actions: {
        addTab(tab) {
            const isExist = this.tabs.some((item) => item.path === tab.path)
            if (!isExist) {
                this.tabs.push(tab)
            }
            this.activeTab = tab.path
        },
        removeTab(targetPath) {
            const index = this.tabs.findIndex((item) => item.path === targetPath)
            if (index > 0) {
                this.tabs.splice(index, 1)
                // 返回要跳转的路径
                return this.tabs[index - 1].path
            }
            return null
        },
        // 新增：设置激活的标签
        setActiveTab(path) {
            this.activeTab = path
        },
        // 设置所有标签
        setTabs(tabs) {
            this.tabs = tabs
        },
        // 关闭其他标签
        closeOtherTabs(currentPath) {
            const homeTab = this.tabs[0]
            const currentTab = this.tabs.find((tab) => tab.path === currentPath)
            if (currentTab) {
                this.tabs = [homeTab]
                if (currentTab.path !== homeTab.path) {
                    this.tabs.push(currentTab)
                }
                this.activeTab = currentPath
            }
        },
        // 关闭所有标签
        closeAllTabs() {
            const homeTab = this.tabs[0]
            this.tabs = [homeTab]
            this.activeTab = homeTab.path
            return homeTab.path
        }
    },
    persist: {
        key: 'tabs',
        storage: localStorage
    }
})
